package com.itheima.tlias.interceptor;

import com.itheima.tlias.utils.CurrentHolder;
import com.itheima.tlias.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		//获取jwt
		String jwt = request.getHeader("token");
		if (jwt == null || jwt.isEmpty()) {
			response.setStatus(HttpStatus.SC_UNAUTHORIZED);
			return false;
		}

		//验证token
		try {
			Claims claims = JwtUtils.parseJWT(jwt);
			int empId = Integer.parseInt(claims.get("id").toString());
			CurrentHolder.setCurrentId(empId);
		} catch (Exception e) {
			response.setStatus(HttpStatus.SC_UNAUTHORIZED);
			return false;
		}

		//放行
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		CurrentHolder.remove();
	}
}
